package com.ruan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruan.common.Code;
import com.ruan.common.Result;
import com.ruan.mapper.ToolBorrowRecordsMapper;
import com.ruan.mapper.ToolsMapper;
import com.ruan.mapper.EmployeeMapper;
import com.ruan.pojo.*;
import com.ruan.service.DepartmentService;
import com.ruan.service.ToolsService;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;

@Service
@Transactional
public class ToolsServiceImpl extends ServiceImpl<ToolsMapper, Tools> implements ToolsService {

    @Resource
    private EmployeeMapper employeeMapper;

    @Resource
    private ToolsService toolsService;

    @Resource
    private DepartmentService departmentService;

    @Resource
    private ToolsMapper toolsMapper;

    @Resource
    private ToolBorrowRecordsMapper toolBorrowRecordsMapper;

    /**
     * 将工具信息导出为Excel
     * @throws Exception
     * @return
     */
    @Override
    public byte[] exportToExcel() {
        List<Tools> toolsList = toolsMapper.selectList(null);
//        为在调用PoiUtils类的exportClientInfo方法时，该方法是非静态方法，
//        而你是通过类名直接调用的，需要先创建PoiUtils对象再调用该方法。
//        PoiUtils poiUtils = new PoiUtils();
//        poiUtils.exportClientInfo(clientList);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        XSSFWorkbook excel=new XSSFWorkbook(); //工作簿，允许您在Java应用程序中创建、读取和修改Excel文件
        //创建一个工作表对象
        XSSFSheet sheet = excel.createSheet("sheet1");

        String[] headers = {"工具名","工具类型",
                "厂商", "单价",
                "库存", "消耗",
                "借出", "所属部门"};

        XSSFRow row1 = sheet.createRow(0); // Create the first row for headers

        for (int i = 0; i < headers.length; i++) {
            row1.createCell(i).setCellValue(headers[i]); // Create cell for each header
        }

        for (int i = 0; i < toolsList.size(); i++) {
            Tools tool = toolsList.get(i);
            XSSFRow row2 = sheet.createRow(i+1);

//            int SexStatus = tool.getStatus();
//            String SexStatusText = (SexStatus == 1) ? "男" : "女";

            Department department = new Department();

            if(tool != null && tool.getDepartmentId() != null) {
                department = departmentService.getById(tool.getDepartmentId());//报空指针。。。。。。啊啊啊啊
                System.out.println("department是：" + department);
            }

            if(tool != null){
                String[] toolInfo = {
                   tool.getTname(),tool.getType(),
                   tool.getMfrs(), String.valueOf(tool.getPrice()),
                   String.valueOf(tool.getTotal()), String.valueOf(tool.getConsumed()),
                   String.valueOf(tool.getLent()), String.valueOf(department.getName())
                };

                for (int j = 0; j < toolInfo.length; j++) {
                    row2.createCell(j).setCellValue(toolInfo[j]);
                }
            }
        }

        HttpHeaders header = new HttpHeaders();
        header.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
        header.setContentDispositionFormData("attachment", "工具表.xlsx");
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            excel.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return outputStream.toByteArray();

    }

    /**
     * 添加工具
     * @param Tools 前端填写的工具对象
     * @return
     */
    @Override
    public boolean addTools(Tools Tools) {

        String ToolsName = Tools.getTname();
        LambdaQueryWrapper<Tools> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(Tools::getTname,ToolsName);
        Integer count = toolsMapper.selectCount(queryWrapper);
        if (count>0){
            return false;
        }
//        Tools.setManager("暂无");
//        Tools.setPhone("暂无");
//        Tools.setNumber(0);
        toolsMapper.insert(Tools);
        return true;
    }


    /**
     * 根据id删除工具
     * @param id 工具id
     */
    @Override
    public Result deleteTools(Integer id) {

        LambdaQueryWrapper<ToolBorrowRecords> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ToolBorrowRecords::getToolId,id);
        toolBorrowRecordsMapper.delete(queryWrapper);

        toolsMapper.deleteById(id);

        return new Result(Code.DELETE_OK,"工具信息删除成功!");
    }

}
